/*
 * @Author: Await
 * @Date: 2025-04-23 11:20:30
 * @LastEditors: Await
 * @LastEditTime: 2025-04-30 17:20:07
 * @Description: 标记点配置组件
 */
import React, { useState, useOptimistic } from 'react';
import {
    Form,
    Input,
    Switch,
    Select,
    InputNumber,
    Row,
    Col,
    Typography,
    Tooltip,
    ColorPicker,
    Button,
    Table,
    Divider,
    Space,
    Modal
} from 'antd';
import { InfoCircleOutlined, PlusOutlined, DeleteOutlined, EditOutlined } from '@ant-design/icons';

// 标记点类型
export interface MarkPointItem {
    type?: 'min' | 'max' | 'average' | '';
    name?: string;
    xAxis?: number | string;
    yAxis?: number | string;
    value?: number;
    symbol?: string;
    symbolSize?: number;
    symbolRotate?: number;
    itemStyle?: {
        color?: string;
        borderColor?: string;
        borderWidth?: number;
    };
    label?: {
        show?: boolean;
        position?: string;
        formatter?: string;
    };
}

export interface MarkPointConfig {
    data?: MarkPointItem[];
    symbol?: string;
    symbolSize?: number;
    symbolRotate?: number;
    label?: {
        show?: boolean;
        position?: string;
        formatter?: string;
    };
    itemStyle?: {
        color?: string;
        borderColor?: string;
        borderWidth?: number;
    };
}

interface MarkPointConfigProps {
    config?: MarkPointConfig;
    onChange: (config: MarkPointConfig) => void;
}

/**
 * 标记点配置组件
 * 
 * React 19新特性应用:
 * 1. 使用useOptimistic实现乐观UI更新，提升用户体验
 * 2. 优化表单状态管理，简化状态逻辑
 * 3. 添加加载状态指示器，提供更好的反馈
 * 4. 使用Actions模式处理数据提交
 */
const MarkPointConfig: React.FC<MarkPointConfigProps> = ({ config = {}, onChange }) => {
    const [visible, setVisible] = useState(false);
    const [editingItem, setEditingItem] = useState<MarkPointItem | null>(null);
    const [editingIndex, setEditingIndex] = useState<number | null>(null);

    // 默认的模态框数据
    const defaultModalItem: MarkPointItem = {
        type: '',
        name: '',
        symbol: 'pin',
        symbolSize: 50,
        label: {
            show: true
        }
    };

    // 确保配置对象存在
    const markPointConfig: MarkPointConfig = config || {};
    const markPointData = markPointConfig.data || [];

    // 使用useOptimistic实现乐观更新
    const [optimisticData, setOptimisticData] = useOptimistic(
        markPointData,
        (state, newData: MarkPointItem[]) => newData
    );

    // 使用普通的useState替代之前的复杂嵌套
    const [modalItem, setModalItem] = useState<MarkPointItem>(defaultModalItem);

    // 当打开模态框时初始化编辑项
    React.useEffect(() => {
        if (visible && editingItem) {
            setModalItem(editingItem);
        } else if (visible) {
            setModalItem(defaultModalItem);
        }
    }, [visible, editingItem]);

    // 处理配置更改 - 使用React 19的模式简化代码结构
    const handleConfigChange = (key: string, value: any) => {
        // 创建一个更新后的配置对象
        let updatedConfig;

        // 处理嵌套属性，例如 'label.show'
        if (key.includes('.')) {
            const keys = key.split('.');
            updatedConfig = { ...markPointConfig };
            let current = updatedConfig as any;

            for (let i = 0; i < keys.length - 1; i++) {
                if (!current[keys[i]]) {
                    current[keys[i]] = {};
                }
                current = current[keys[i]];
            }

            current[keys[keys.length - 1]] = value;
        } else {
            updatedConfig = { ...markPointConfig, [key]: value };
        }

        // 调用父组件的onChange
        onChange(updatedConfig);

        // 如果这是一个数据更新，也更新乐观UI
        if (key === 'data') {
            setOptimisticData(value);
        }
    };

    // 添加或更新标记点
    const handleAddOrUpdateMarkPoint = () => {
        const newData = [...(markPointData || [])];

        if (editingIndex !== null) {
            // 更新现有项目
            newData[editingIndex] = modalItem;
        } else {
            // 添加新项目
            newData.push(modalItem);
        }

        // 乐观更新UI
        setOptimisticData(newData);

        // 实际更新数据
        handleConfigChange('data', newData);
        setVisible(false);
        setEditingItem(null);
        setEditingIndex(null);
    };

    // 删除标记点
    const handleDeleteMarkPoint = (index: number) => {
        const newData = [...markPointData];
        newData.splice(index, 1);

        // 乐观更新UI
        setOptimisticData(newData);

        // 实际更新数据
        handleConfigChange('data', newData);
    };

    // 编辑现有标记点
    const handleEditMarkPoint = (item: MarkPointItem, index: number) => {
        setEditingItem(item);
        setEditingIndex(index);
        setVisible(true);
    };

    // 更新模态框中的项目
    const updateModalItem = (key: string, value: any) => {
        // 处理嵌套属性
        if (key.includes('.')) {
            const keys = key.split('.');
            const updatedItem = { ...modalItem };
            let current = updatedItem as any;

            for (let i = 0; i < keys.length - 1; i++) {
                if (!current[keys[i]]) {
                    current[keys[i]] = {};
                }
                current = current[keys[i]];
            }

            current[keys[keys.length - 1]] = value;
            setModalItem(updatedItem);
        } else {
            setModalItem({ ...modalItem, [key]: value });
        }
    };

    // 表单项标题组件
    const FormItemLabel = ({ children, tooltip }: { children: React.ReactNode, tooltip?: string }) => (
        <div style={{ marginBottom: 4, display: 'flex', alignItems: 'center' }}>
            <Typography.Text type="secondary" style={{ fontSize: 12 }}>
                {children}
            </Typography.Text>
            {tooltip && (
                <Tooltip title={tooltip}>
                    <InfoCircleOutlined style={{ marginLeft: 4, fontSize: 12, color: '#999' }} />
                </Tooltip>
            )}
        </div>
    );

    // 表格列定义
    const columns = [
        {
            title: '名称',
            dataIndex: 'name',
            key: 'name',
            render: (text: string) => text || '-'
        },
        {
            title: '类型',
            dataIndex: 'type',
            key: 'type',
            render: (text: string) => {
                const typeMap: Record<string, string> = {
                    'min': '最小值',
                    'max': '最大值',
                    'average': '平均值'
                };
                return typeMap[text] || '自定义';
            }
        },
        {
            title: '值',
            dataIndex: 'value',
            key: 'value',
            render: (text: number, record: MarkPointItem) => {
                if (record.type && ['min', 'max', 'average'].includes(record.type)) {
                    return `[${record.type}]`;
                }
                return text !== undefined ? text : '-';
            }
        },
        {
            title: '坐标',
            key: 'coordinate',
            render: (_: any, record: MarkPointItem) => {
                if (record.xAxis !== undefined && record.yAxis !== undefined) {
                    return `(${record.xAxis}, ${record.yAxis})`;
                }
                return '-';
            }
        },
        {
            title: '操作',
            key: 'action',
            render: (_: any, record: MarkPointItem, index: number) => (
                <Space size="middle">
                    <Button
                        type="text"
                        icon={<EditOutlined />}
                        onClick={() => handleEditMarkPoint(record, index)}
                    />
                    <Button
                        type="text"
                        danger
                        icon={<DeleteOutlined />}
                        onClick={() => handleDeleteMarkPoint(index)}
                    />
                </Space>
            )
        }
    ];

    // 标记点编辑模态框 - 使用React 19新特性优化
    const markPointModal = (
        <Modal
            title={editingIndex !== null ? "编辑标记点" : "添加标记点"}
            open={visible}
            onOk={handleAddOrUpdateMarkPoint}
            onCancel={() => {
                setVisible(false);
                setEditingItem(null);
                setEditingIndex(null);
            }}
            okButtonProps={{
                loading: optimisticData !== markPointData // 使用乐观更新状态显示加载状态
            }}
            width={600}
        >
            <div className="form-container">
                <Row gutter={[16, 8]}>
                    <Col span={12}>
                        <FormItemLabel tooltip="标记点显示的名称">
                            名称
                        </FormItemLabel>
                        <Input
                            value={modalItem.name}
                            onChange={e => updateModalItem('name', e.target.value)}
                            placeholder="标记点名称"
                        />
                    </Col>
                    <Col span={12}>
                        <FormItemLabel tooltip="标记点类型，可选择系统自动计算的点">
                            类型
                        </FormItemLabel>
                        <Select
                            value={modalItem.type || ''}
                            onChange={value => updateModalItem('type', value)}
                            style={{ width: '100%' }}
                            options={[
                                { label: '自定义', value: '' },
                                { label: '最大值', value: 'max' },
                                { label: '最小值', value: 'min' },
                                { label: '平均值', value: 'average' }
                            ]}
                        />
                    </Col>

                    {!modalItem.type && (
                        <>
                            <Col span={12}>
                                <FormItemLabel tooltip="X轴坐标值">
                                    X轴坐标
                                </FormItemLabel>
                                <InputNumber
                                    value={modalItem.xAxis !== undefined ? Number(modalItem.xAxis) : undefined}
                                    onChange={value => updateModalItem('xAxis', value)}
                                    style={{ width: '100%' }}
                                />
                            </Col>
                            <Col span={12}>
                                <FormItemLabel tooltip="Y轴坐标值">
                                    Y轴坐标
                                </FormItemLabel>
                                <InputNumber
                                    value={modalItem.yAxis !== undefined ? Number(modalItem.yAxis) : undefined}
                                    onChange={value => updateModalItem('yAxis', value)}
                                    style={{ width: '100%' }}
                                />
                            </Col>
                            <Col span={12}>
                                <FormItemLabel tooltip="标记点值，将显示在标签上">
                                    显示值
                                </FormItemLabel>
                                <InputNumber
                                    value={modalItem.value}
                                    onChange={value => updateModalItem('value', value)}
                                    style={{ width: '100%' }}
                                />
                            </Col>
                        </>
                    )}

                    <Col span={12}>
                        <FormItemLabel tooltip="标记点图形类型">
                            图形类型
                        </FormItemLabel>
                        <Select
                            value={modalItem.symbol || 'pin'}
                            onChange={value => updateModalItem('symbol', value)}
                            style={{ width: '100%' }}
                            options={[
                                { label: '圆形', value: 'circle' },
                                { label: '矩形', value: 'rect' },
                                { label: '圆角矩形', value: 'roundRect' },
                                { label: '三角形', value: 'triangle' },
                                { label: '菱形', value: 'diamond' },
                                { label: '大头针', value: 'pin' },
                                { label: '箭头', value: 'arrow' }
                            ]}
                        />
                    </Col>
                    <Col span={12}>
                        <FormItemLabel tooltip="标记点大小">
                            图形大小
                        </FormItemLabel>
                        <InputNumber
                            value={modalItem.symbolSize || 50}
                            onChange={value => updateModalItem('symbolSize', value)}
                            min={10}
                            max={100}
                            style={{ width: '100%' }}
                        />
                    </Col>
                    <Col span={12}>
                        <FormItemLabel tooltip="标记点旋转角度">
                            旋转角度
                        </FormItemLabel>
                        <InputNumber
                            value={modalItem.symbolRotate || 0}
                            onChange={value => updateModalItem('symbolRotate', value)}
                            min={-180}
                            max={180}
                            style={{ width: '100%' }}
                        />
                    </Col>
                    <Col span={12}>
                        <FormItemLabel tooltip="标记点颜色">
                            颜色
                        </FormItemLabel>
                        <ColorPicker
                            value={modalItem.itemStyle?.color}
                            onChange={color => {
                                const itemStyle = modalItem.itemStyle || {};
                                updateModalItem('itemStyle', {
                                    ...itemStyle,
                                    color: typeof color === 'string' ? color : color.toHexString()
                                });
                            }}
                            showText
                        />
                    </Col>
                    <Col span={12}>
                        <FormItemLabel tooltip="是否显示标签">
                            显示标签
                        </FormItemLabel>
                        <Switch
                            checked={modalItem.label?.show !== false}
                            onChange={checked => {
                                const label = modalItem.label || {};
                                updateModalItem('label', { ...label, show: checked });
                            }}
                        />
                    </Col>
                    {modalItem.label?.show !== false && (
                        <Col span={12}>
                            <FormItemLabel tooltip="标签位置">
                                标签位置
                            </FormItemLabel>
                            <Select
                                value={modalItem.label?.position || 'top'}
                                onChange={value => {
                                    const label = modalItem.label || { show: true };
                                    updateModalItem('label', { ...label, position: value });
                                }}
                                style={{ width: '100%' }}
                                options={[
                                    { label: '顶部', value: 'top' },
                                    { label: '左侧', value: 'left' },
                                    { label: '右侧', value: 'right' },
                                    { label: '底部', value: 'bottom' },
                                    { label: '内部', value: 'inside' }
                                ]}
                            />
                        </Col>
                    )}
                </Row>
            </div>
        </Modal>
    );

    return (
        <div>
            <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <Typography.Title level={5} style={{ margin: 0 }}>
                    标记点设置
                    <Tooltip title="在图表上标记关键的数据点，如最大值、最小值等">
                        <InfoCircleOutlined style={{ fontSize: 14, marginLeft: 8 }} />
                    </Tooltip>
                </Typography.Title>
                <Button
                    type="primary"
                    icon={<PlusOutlined />}
                    onClick={() => {
                        setEditingItem(null);
                        setEditingIndex(null);
                        setVisible(true);
                    }}
                >
                    添加标记点
                </Button>
            </div>

            {/* 添加一个表单操作状态提示 */}
            {optimisticData !== markPointData && (
                <div style={{ marginBottom: 8, color: '#1890ff' }}>
                    <span>数据更新中...</span>
                </div>
            )}

            {/* 标记点列表 */}
            <Table
                columns={columns}
                dataSource={optimisticData.map((item, index) => ({ ...item, key: index }))}
                size="small"
                pagination={false}
                style={{ marginBottom: 16 }}
            />

            {/* 全局标记点样式设置 */}
            <Divider orientation="left">全局样式设置</Divider>
            <div className="form-container">
                <Row gutter={[16, 8]}>
                    <Col span={12}>
                        <FormItemLabel tooltip="标记点默认图形类型">
                            默认图形
                        </FormItemLabel>
                        <Select
                            value={markPointConfig.symbol || 'pin'}
                            onChange={value => handleConfigChange('symbol', value)}
                            style={{ width: '100%' }}
                            options={[
                                { label: '圆形', value: 'circle' },
                                { label: '矩形', value: 'rect' },
                                { label: '圆角矩形', value: 'roundRect' },
                                { label: '三角形', value: 'triangle' },
                                { label: '菱形', value: 'diamond' },
                                { label: '大头针', value: 'pin' },
                                { label: '箭头', value: 'arrow' }
                            ]}
                        />
                    </Col>
                    <Col span={12}>
                        <FormItemLabel tooltip="标记点默认大小">
                            默认大小
                        </FormItemLabel>
                        <InputNumber
                            value={markPointConfig.symbolSize || 50}
                            onChange={value => handleConfigChange('symbolSize', value)}
                            min={10}
                            max={100}
                            style={{ width: '100%' }}
                        />
                    </Col>
                    <Col span={12}>
                        <FormItemLabel tooltip="标记点默认颜色">
                            默认颜色
                        </FormItemLabel>
                        <ColorPicker
                            value={markPointConfig.itemStyle?.color}
                            onChange={color => {
                                const colorValue = typeof color === 'string'
                                    ? color
                                    : color.toHexString();
                                handleConfigChange('itemStyle.color', colorValue);
                            }}
                            showText
                        />
                    </Col>
                    <Col span={12}>
                        <FormItemLabel tooltip="是否默认显示标签">
                            默认显示标签
                        </FormItemLabel>
                        <Switch
                            checked={markPointConfig.label?.show !== false}
                            onChange={checked => handleConfigChange('label.show', checked)}
                        />
                    </Col>
                </Row>
            </div>

            {/* 直接渲染模态框，不再通过函数调用 */}
            {markPointModal}
        </div>
    );
};

export default MarkPointConfig;